package com.lemon.stock.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lemon.stock.app.StockApplication
import com.lemon.stock.entity.Batch
import com.lemon.stock.entity.Stock
import com.lemon.stock.entity.Trade
import kotlinx.coroutines.launch

class HistoryViewModel: ViewModel() {
    private val _stocks = MutableLiveData<List<Stock>>()
    private val _stock = MutableLiveData<Stock>()
    private val _batches = MutableLiveData<List<Batch>>()
    private val _trades = MutableLiveData<List<Trade>>()

    val stocks: LiveData<List<Stock>>
        get() = _stocks
    val stock: LiveData<Stock>
        get() = _stock
    val batches: LiveData<List<Batch>>
        get() = _batches
    val trades: LiveData<List<Trade>>
        get() = _trades


    fun fetchStocks(){
        viewModelScope.launch {
            val stockDao = StockApplication.getDataRoom().stockDao()
            val liStock = stockDao.allStocks()
            _stocks.postValue(liStock)
        }
    }

    fun fetchStock(id: String){
        viewModelScope.launch {
            val stockDao = StockApplication.getDataRoom().stockDao()
            val siStock = stockDao.findById(id)
            _stock.postValue(siStock)
        }
    }

    fun fetchBatches(stockId: String){
        viewModelScope.launch {
            val batchDao = StockApplication.getDataRoom().batchDao()
            val liBatches = batchDao.getList(stockId)
            _batches.postValue(liBatches)
        }
    }

    fun fetchTrades(stockId: String, index: Int){
        viewModelScope.launch {
            val tradeDao = StockApplication.getDataRoom().tradeDao()
            val liTrades:List<Trade> = when(index){
                -1 -> tradeDao.surveyTrades(stockId)
                else -> tradeDao.surveyTrades(stockId, index)
            }
            _trades.postValue(liTrades)
        }
    }

    fun updateStock(stock: Stock){
        val stockDao = StockApplication.getDataRoom().stockDao()
        stockDao.update(stock)
    }
}